
import React from 'react';
import { Map ,MouseTool} from 'react-amap';
import {  Input ,message} from 'antd';
import './index.less';
let map ;
let timeout;
let currentValue;
interface IMap {
  longitude: string;
  latitude: string;
}

interface IState{
  center:IMap,
  amapkey:string,
  suggestions:string[],
  searchMsg:string,
  mapInstance:any,
  placeSearch:any,
  isSelect:boolean,
  tool:any,
  geocoder:any,
  nowAdd:string,
  adcode:string,
  marker:any
}
interface IProps{
  center:IMap,
  setMeetAddrMap:any,
  address?:string,
  adcode?:string
}
class MapChoose extends React.Component<IProps, IState> {
  constructor(props:any){
    super(props);
    this.state = {
      center:{longitude:116.397474,latitude:39.908696},//默认北京
      amapkey:'6df74111810dc36211228366be6bea88',
      suggestions:[],
      searchMsg:undefined,
      mapInstance:undefined,
      placeSearch:undefined,
      isSelect:false,
      tool:undefined,
      geocoder:undefined,
      nowAdd:props.address?props.address:"",
      adcode:props.adcode?props.adcode:"",
      marker:undefined

    };
  }



  handleSearch = (event) => {
    this.fetch(event.target.value);
  }


fetch = (value)=> {
  if (timeout) {
    clearTimeout(timeout);
    timeout = null;
  }
  currentValue = value;
  let self = this;

  function fake() {
  
  self.state.placeSearch.search(currentValue);

  }

  timeout = setTimeout(fake, 1000);
}


  render() {
    let self = this;

    const mapEvents = {
      created: (mapInstance) => {
        this.setState({ mapInstance: mapInstance });
        map = mapInstance;
        //经纬度换地址
        window.AMap.service(["AMap.Geocoder"], function() {

            let  geocoder = new AMap.Geocoder({
            });
            self.setState({
              geocoder:geocoder
            })

        })
        if(self.props.center && self.props.center.latitude &&self.props.center.longitude && self.props.center.latitude !=0 && self.props.center.longitude != 0){
              self.setState({
                // nowAdd:item.selected.data.name,
                center: self.props.center

              })

              var lnglat  = self.props.center.longitude+","+self.props.center.latitude;
              let address = self.props.address?self.props.address:"";
              if(address === ""){
              self.state.geocoder.getAddress(lnglat, function(status, result) {
                  if (status === 'complete'&&result.regeocode) {
                      address = result.regeocode.formattedAddress;
                      self.setState({
                        nowAdd:address,
                      })
                  }
                  var marker = new AMap.Marker({
                    position: new AMap.LngLat(self.props.center.longitude, self.props.center.latitude ),   // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
                    title: address
                  });
                  // 将创建的点标记添加到已有的地图实例：
                  map.add(marker);
                  self.setState({
                    marker: marker
                  })
                  self.props.setMeetAddrMap(self.props.center,address);
              });
            }else{

              var marker = new AMap.Marker({
                position: new AMap.LngLat(self.props.center.longitude, self.props.center.latitude ),   // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
                title: address
              });
              // 将创建的点标记添加到已有的地图实例：
              map.add(marker);
              self.setState({
                marker: marker
              })
              self.props.setMeetAddrMap(self.props.center,address);
            }

        }else{
          AMap.plugin('AMap.Geolocation', function() {
            var geolocation = new AMap.Geolocation({

            });
            // map.addControl(geolocation);
            geolocation.getCurrentPosition(function(status,result){
                if(status=='complete'){
                  self.setState({
                    // nowAdd:item.selected.data.name,
                    center: {
                      longitude:result.position.lng,
                      latitude:result.position.lat
                    },
                    nowAdd:""


                  })
                }
            });
        });

        }

        //关键词搜索
        window.AMap.service(["AMap.PlaceSearch"], function() {
          //构造地点查询类
          let placeSearch = new AMap.PlaceSearch({
              pageSize: 5, // 单页显示结果条数
              pageIndex: 1, // 页码
              // city: "010", // 兴趣点城市
              // citylimit: true,  //是否强制限制在设置的城市内搜索
              map: map, // 展现结果的地图实例
              panel: "mapPanel", // 结果列表将在此容器中进行展示。
              autoFitView: true // 是否自动调整地图视野使绘制的 Marker点都处于视口的可见范围
          });
          //关键字查询
          placeSearch.on("selectChanged",(item)=>{
            self.setState({
              isSelect:true
            })
            self.state.tool.close(true);
            setTimeout(()=>{
              self.setState({
                isSelect:false
              })
              self.state.tool.marker();
            }, 1000);

            self.setState({
              nowAdd:item.selected.data.name,
              center: {
                longitude: item.selected.data.location.lng,
                latitude: item.selected.data.location.lat,
              }

            })
            self.props.setMeetAddrMap({
              longitude: item.selected.data.location.lng,
              latitude: item.selected.data.location.lat,
            },item.selected.data.name,item.selected.data.adcode)
          })
          self.setState({
            placeSearch:placeSearch
          })
      });
      },
      click: () => {
        
      },
    }

      const toolEvents = {
          created: (tool) => {
              tool.marker();
              self.setState({
                  tool:tool
              })
              // tool.close(true);
              // self.tool = tool;
          },
          draw({obj}) {
              if(self.state.marker){
                  self.state.mapInstance.remove(self.state.marker);
              }
              if(self.state.isSelect){
              }else{
                  self.state.tool.close(true);
                  self.state.tool.marker();
                  self.state.placeSearch.clear();
                  //有时候ce有时候de。好吧。我做个判断
                  let position;
                  if('Ce' in obj){
                      position=obj.Ce.position;
                  }else if('De' in obj){
                      position=obj.De.position;
                  }


                  var lnglat  = position.lng+","+position.lat;

                  self.state.geocoder.getAddress(lnglat, function(status, result) {
                      if (status === 'complete'&&result.regeocode) {
                          var address = result.regeocode.formattedAddress;
                          let adcode=result.regeocode.addressComponent.adcode;
                          self.setState({
                              nowAdd:address,
                              adcode:adcode,
                              center: {
                                  longitude: position.lng,
                                  latitude: position.lat,
                              }
                          })
                          
                          self.props.setMeetAddrMap( {
                              longitude: position.lng,
                              latitude: position.lat,
                          },address,adcode)
                      }else{

                      }
                  });
              }
          }
      }

    const { amapkey, nowAdd} = this.state;

    return <div className="relative-div">
      <div style={{width: '100%', height: '100%'}} >
      <div id = "mapPanel" className="mapPanel"></div>
        <Map  events={mapEvents} plugins={['ToolBar']} zoom={15} amapkey={amapkey} center={this.state.center}>
          <MouseTool events={toolEvents}/>
        </Map>
      </div>
      <Input
        className ="mapSearchInput"
        placeholder="请输入地名搜索"
        onChange={this.handleSearch}
      />
      {nowAdd!==""?<div className="showNowAdd">当前选择：{nowAdd}</div>:""}
    </div>
  }
}


export default MapChoose;
